package com.loan.market.ui

import android.Manifest
import android.content.Intent
import android.os.Bundle
import androidx.core.widget.addTextChangedListener
import com.loan.market.R
import com.loan.market.base.BaseBindingActivity
import com.loan.market.bean.User
import com.loan.market.databinding.ActivityLoginBinding
import com.loan.market.databinding.DialogPermissionBinding
import com.loan.market.databinding.DialogSingleBtnBinding
import com.loan.market.event.LoginEvent
import com.loan.market.http.getHttpMap
import com.loan.market.http.request
import com.loan.market.util.*
import com.permissionx.guolindev.PermissionX
import org.greenrobot.eventbus.EventBus

class LoginActivity : BaseBindingActivity<ActivityLoginBinding>() {

    override fun getViewBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun initUi(savedInstanceState: Bundle?) {
        afEvent("enter_signlog")
        transparentStatusBar()
        statusBarFont(true)
        binding.tvTerm.appendClickText("Términos de Uso") {
            getConfig {
                val intent = Intent(this, WebActivity::class.java)
                intent.putExtra("url", it.protocolUrls?.useTermsUrl)
                intent.putExtra("title", getString(R.string.terms_of_use))
                startActivity(intent)
            }
        }
        binding.tvTerm.append(" y la ")
        binding.tvTerm.appendClickText(" Política de Privacidad ") {
            getConfig {
                val intent = Intent(this, WebActivity::class.java)
                intent.putExtra("url", it.protocolUrls?.privicyPolicyUrl)
                intent.putExtra("title", getString(R.string.privacy_policy))
                startActivity(intent)
            }
        }
    }

    override fun initEvent() {
        binding.etPhone.addTextChangedListener {
            binding.tvSendCode.isEnabled = !it.isNullOrBlank() && it.length == 10
            binding.btnLogin.isEnabled = !it.isNullOrBlank() && it.length == 10 && !binding.etCode.text.isNullOrBlank()
        }
        binding.etCode.addTextChangedListener {
            binding.btnLogin.isEnabled = !it.isNullOrBlank() && !binding.etPhone.text.isNullOrBlank() && binding.etPhone.text.length == 10
        }
        binding.tvSendCode.setOnClickListener {
            http(onFinish = ::dismissLoading) {
                showLoading()
                val map = getHttpMap(101)
                map["phone"] = binding.etPhone.text.toString()
                map["codeType"] = 200
                request<Any>(map)
                timer { time, finish ->
                    binding.tvSendCode.isEnabled = finish
                    if (finish) {
                        binding.tvSendCode.text = "Reenviar"
                    } else {
                        binding.tvSendCode.text = "$time s"
                    }
                }
            }
        }
        binding.btnLogin.setOnClickListener {
            if (!binding.cbTerm.isChecked) {
                val bind = DialogSingleBtnBinding.inflate(layoutInflater)
                bind.tvContent.text = "Debes marcar la casilla para aceptar los Términos de Uso y la Política de Privacidad."
                val dialog = showDialog(bind.root)
                bind.btnConfirm.setOnClickListener { dialog.dismiss() }
                return@setOnClickListener
            }
            afEvent("click_signlog")
            http(onFinish = ::dismissLoading) {
                showLoading()
                val map = getHttpMap(102)
                val phone = binding.etPhone.text.toString()
                map["phone"] = phone
                map["checkCode"] = binding.etCode.text.toString()
                val user = request<User>(map)
                user?.phone = phone
                UserUtil.login(user)
                EventBus.getDefault().post(LoginEvent())
                permissionDialog()
            }
        }
    }

    private fun permissionDialog() {
        val bind = DialogPermissionBinding.inflate(layoutInflater)
        val dialog = showDialog(bind.root)
        dialog.setCancelable(false)
        bind.btnLater.setOnClickListener {
            dialog.dismiss()
            startActivity(Intent(activity, MainActivity::class.java))
            finish()
        }
        bind.btnConfirm.setOnClickListener {
            dialog.dismiss()
            PermissionX.init(activity)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS)
                .request { _, _, _ ->
                    startActivity(Intent(activity, MainActivity::class.java))
                    finish()
                }
        }
    }

    override fun initData() {

    }
}